package com.example.demo.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author MarioZzz
 * @create 2023-11-15 9:31
 */
public class MyBatisUtils {
    public static SqlSession getSession() {
        SqlSession session = null;
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            // mybatis增、删、改要手动提交事务，true表示自动提交事务
            session = sqlSessionFactory.openSession(true);
            return session;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void closeSession(SqlSession session) {
        if (session != null) {
            session.close();
        }
    }
}

